package com.doyens.controller;

import com.alibaba.druid.util.StringUtils;
import com.doyens.pojo.DTO;
import com.doyens.pojo.Student;
import com.doyens.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * //查询所有
     * 分页查询
     * 注意判断pageNum和pageSize是否为空
     * 若为空，需要处理
     */
    @RequestMapping("/findAll.do")
    public String findAllStu(Model model, String pageNum, Integer pageSize) {
        PageInfo<Student> page = studentService.findAll(pageNum, pageSize);
        model.addAttribute("page", page);
        return "list";
    }

    /**
     * 根据id删除，注意先删除从表
     * 再删除主表
     */
    @RequestMapping("/del.do")
    public String del(Integer id) {
        int i = studentService.del(id);
//        根据返回值确定是否删除成功
        if (i != 0) {
            return "list";
        }
        return "error";
    }

    /**
     * 添加对象，多表添加
     * 注意先添加从表数据
     * 再添加主表对象
     */
    @RequestMapping("/save.do")
    public String save(Student student, Integer[] scheduleIds, MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        file.transferTo(new File("D:/IDEA-workspace/p4/ssm-work02-10.30/ssm-web/src/main/webapp/image" + filename));
        student.setPhoto("/pages/" + filename + ".png");
        //再存储学生对象
        studentService.save(student,scheduleIds);
        return "list";
    }

    /**
     * 条件查询注意判断条件是否为空
     */
    @RequestMapping("/findByCondition.do")
    public String findByCondition(DTO dto){
        studentService.findByCondition(dto);
        return "list";
    }
}

